package com.yuanluludev.lib_base.base

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentTransaction
import com.yuanluludev.lib_base.R
import com.yuanluludev.lib_base.ext.toastFailedMiddle

/**
 * yuanLuLu
 * 通用Activity 用于装载fragment
 */
class CommonActivity : BaseActivity() {

    private var fragment: BaseFragment? = null

    companion object {

        private const val BUNDLE_PARAMS = "bundle_params"

        private const val FRAGMENT_NAME = "fragment_name"

        private const val IS_STATUS_BAR_DEFAULT = "is_status_bar_default"

        @JvmStatic
        fun startNewFragment(
            context: FragmentActivity?,
            clazz: Class<*>,
            bundle: Bundle? = null,
            isStatusBarDefault: Boolean = false
        ) {
            context?.startActivity(Intent(context, CommonActivity::class.java).apply {
                putExtra(FRAGMENT_NAME, clazz.name)
                bundle?.let { putExtra(BUNDLE_PARAMS, it) }
                putExtra(IS_STATUS_BAR_DEFAULT, isStatusBarDefault)
            })
        }

        @JvmStatic
        fun startNewFragmentForClazzStr(
            context: FragmentActivity?,
            clazz: String,
            bundle: Bundle? = null,
            isStatusBarDefault: Boolean = false
        ) {
            context?.startActivity(Intent(context, CommonActivity::class.java).apply {
                putExtra(FRAGMENT_NAME, clazz)
                bundle?.let { putExtra(BUNDLE_PARAMS, it) }
                putExtra(IS_STATUS_BAR_DEFAULT, isStatusBarDefault)
            })
        }

        @JvmStatic
        fun startNewFragmentForResult(
            context: FragmentActivity?,
            clazz: Class<*>,
            bundle: Bundle? = null,
            requestCode: Int,
            isStatusBarDefault: Boolean = true
        ) {
            context?.startActivityForResult(
                Intent(
                    context,
                    CommonActivity::class.java
                ).apply {
                    putExtra(FRAGMENT_NAME, clazz.name)
                    bundle?.let { putExtra(BUNDLE_PARAMS, it) }
                    putExtra(IS_STATUS_BAR_DEFAULT, isStatusBarDefault)
                }, requestCode
            )
        }

    }

    override fun afterLoadLayout(savedInstanceState: Bundle?) {

        intent?.getBooleanExtra(IS_STATUS_BAR_DEFAULT, true)?.let {

        }

        val bundle = intent?.getBundleExtra(BUNDLE_PARAMS)
        val clazzName = intent?.getStringExtra(FRAGMENT_NAME)

        clazzName?.let {
            try {
                //不为null，说明是死而复活，移除已经存在的fragment 避免fragment重影
                if (savedInstanceState != null && !supportFragmentManager.isDestroyed) {
                    val transaction: FragmentTransaction =
                        this.supportFragmentManager.beginTransaction()
                    val fra: Fragment? = supportFragmentManager.findFragmentByTag(clazzName)
                    if (fra != null) {
                        transaction.remove(fra)
                        transaction.commitNowAllowingStateLoss()
                    }
                }

                fragment = Class.forName(clazzName).newInstance() as BaseFragment?
                bundle?.let {
                    fragment?.arguments = it
                }
                supportFragmentManager.beginTransaction()
                    .add(R.id.rootLayout, fragment ?: return, clazzName)
                    .commitNowAllowingStateLoss()

            } catch (e: Exception) {
                showErrorToast()
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        fragment?.onActivityResult(requestCode, resultCode, data)
    }

    private fun showErrorToast() = "页面加载错误，请稍后重试！".toastFailedMiddle()

    override fun getLayoutResId() = R.layout.activity_common_with_fragment

}
